export default {
    namespaced: true,
    state: () => {
        // 从localStorage获取用户信息
        const userInfo = localStorage.getItem('userInfo');
        const merchantInfo = localStorage.getItem('merchantInfo');
        let userinfo = {
            token: '',
            username: '',
            userId: ''
        };
        
        // 优先使用商家信息，如果没有则使用普通用户信息
        if (merchantInfo) {
            try {
                const parsed = JSON.parse(merchantInfo);
                userinfo = {
                    token: parsed.token || '',
                    username: parsed.merchantName || '',
                    userId: parsed.merchantId || ''
                };
            } catch (e) {
                // 解析失败则尝试使用普通用户信息
                if (userInfo) {
                    try {
                        const parsed = JSON.parse(userInfo);
                        userinfo = {
                            token: parsed.token || '',
                            username: parsed.username || '',
                            userId: parsed.userId || ''
                        };
                    } catch (e) {
                        // 解析失败则使用默认值
                    }
                }
            }
        } else if (userInfo) {
            try {
                const parsed = JSON.parse(userInfo);
                userinfo = {
                    token: parsed.token || '',
                    username: parsed.username || '',
                    userId: parsed.userId || ''
                };
            } catch (e) {
                // 解析失败则使用默认值
            }
        }
        
        return {
            userinfo
        }
    },
    mutations: {
        updateName(state, payload) {
            state.userinfo.username = payload;
        },
        // 添加更新用户信息的mutation
        updateUserInfo(state, payload) {
            state.userinfo = {
                token: payload.token || '',
                username: payload.username || payload.merchantName || '',
                userId: payload.userId || payload.merchantId || ''
            };
        }
    },
    actions:{
        updateNameAsync({commit},payload){
            setTimeout(() => {
                commit('updateName',payload)
            }, 2000);
        }
    },
    getters:{
        
    }
}